/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.rcs.servlets.utils;

import org.rcs.servlets.exceptions.InvalidRangeException;

// Inner classes ------------------------------------------------------------------------------

/**
 * This class represents a byte range.
 */
public class Range {
  private long start;
  private long end;
  private long length;
  private long total;

  /**
   * Construct a byte range.
   *
   * @param start Start of the byte range.
   * @param end End of the byte range.
   * @param total Total length of the byte source.
   */
  /**
   * Construct a byte range.
   *
   * @param start Start of the byte range.
   * @param end End of the byte range.
   * @param total Total length of the byte source.
   */
  public Range(long start, long end, long total) {
    this.start = start;
    this.end = end;
    this.length = end - start + 1;
    this.total = total;
  }

  /**
   * Returns a substring of the given string value from the given begin index to the given end index as a long. If the substring is empty, then -1 will be
   * returned
   *
   * @param value The string value to return a substring as long for.
   * @param beginIndex The begin index of the substring to be returned as long.
   * @param endIndex The end index of the substring to be returned as long.
   * @return A substring of the given string value as long or -1 if substring is empty.
   */
  private static long sublong(String value, int beginIndex, int endIndex) {
    String substring = value.substring(beginIndex, endIndex);
    return (substring.length() > 0) ? Long.parseLong(substring) : -1;
  }

  public static Range createFrom(String part, long length) throws InvalidRangeException {
    // Assuming a file with length of 100, the following examples returns bytes at:
    // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
    long start = sublong(part, 0, part.indexOf("-"));
    long end = sublong(part, part.indexOf("-") + 1, part.length());
    if (start == -1) {
      start = length - end;
      end = length - 1;
    }
    else if (end == -1 || end > length - 1)
      end = length - 1;
    // Check if Range is syntactically valid. If not, then return 416.
    if (start > end)
      throw new InvalidRangeException(start, end);
    return new Range(start, end, length);
  }

  /**
   * @return the start
   */
  public long getStart() {
    return start;
  }

  /**
   * @return the end
   */
  public long getEnd() {
    return end;
  }

  /**
   * @return the length
   */
  public long getLength() {
    return length;
  }

  /**
   * @return the total
   */
  public long getTotal() {
    return total;
  }
}
